import React, { useState } from 'react';
import s from './style.module.css';
import { Message, Button, Form, Input, Switch } from '@knownsec/react-component';
import recursionForm from '@/common/recursionForm';
import { getNetmap, putNetmap } from '~/API';
export default function email() {
  const [createForm] = Form.useForm();
  const [isMap, setIsMap] = useState(false);
  const validatormap = (rule, value, callback) => {
    return Promise.resolve();
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    if({}.propertyIsEnumerable.call(values, "net_map_disabled")){
      setIsMap(values.net_map_disabled)
    }
    createForm.current.setFieldsValue(values);
  };
  const sendForm = () => {
    createForm.current.validateFields().then(async (res) => {
      const res_=res
      res_.net_map_disabled=!res.net_map_disabled
      res_.net_map_disabled&&delete res_.net_map_host
      const putres = await putNetmap(res_).catch((e)=>{return e});
      if (putres.status === 'success') {
        Message.show({
          pro: true,
          type: 'success',
          message: '修改成功',
          showClose: false,
        });
      }else{
        const keyforms = {
          net_map_host: '映射设置',
        };
        const errmsg =
        keyforms[Object.keys(putres.data)[0]] + ': ' + Object.values(putres.data)[0] || '操作失败';
        const errmsg_=errmsg.replace('undefined:','')
        Message.show({
          pro: true,
          type: 'error',
          message: errmsg_,
          showClose: false,
        });
      }
    });
  };
  React.useEffect(async () => {
    const res = await getNetmap();
    const data=res.data.data
    data.net_map_disabled=!data.net_map_disabled
    setIsMap(data.net_map_disabled)
    createForm.current.setFieldsValue(data);
  }, []);
  return (
    <div className={s.emailBox}>
      <Form
        ref={createForm}
        onValuesChange={(newItem, allValues) => {
          onValues(newItem, allValues);
        }}
      >
        <Form.Item
          rules={[{ required: false, validator: validatormap }]}
          name="net_map_disabled"
          label="外网映射"
          valuePropName="checked"
        >
          <Switch pro></Switch>
        </Form.Item>
        <Form.Item
          rules={[{ required: true, validator: validatormap }]}
          name="net_map_host"
          label="映射设置"
        >
          <Input
            pro
            className={s.inpName}
            maxlength={50}
            placeholder="请输入映射地址"
            autoComplete={'off'}
            disabled={!isMap}
          ></Input>
        </Form.Item>
        <div className={s.tips}>例如: http://www.example.com/, http://100.100.100.10, https://www.example.com, https://100.100.100.10</div>
      </Form>
      <Button
        pro
        type="primary"
        className={s.btn}
        onClick={() => {
          sendForm();
        }}
      >
          确定
      </Button>
    </div>
  );
}
